/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.proyecto.iu;

import com.google.gson.Gson;
import com.proyecto.bl.Documento;
import com.proyecto.bl.Service;
import com.proyecto.bl.Usuario;
import com.proyecto.dal.UsuarioDao;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author BlueDeep
 */
@WebServlet(name = "ConsultarLibros", urlPatterns = {"/ConsultarLibros"})
public class ConsultarLibros extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int opc = 0;
        PrintWriter out = response.getWriter();
        ArrayList documentos = new ArrayList();
        try {

            opc = Integer.parseInt(request.getParameter("p1"));
            Gson gSon = new Gson();
            
            HttpSession s = request.getSession();
            Object o = s.getAttribute("usuario");
            String permisos = "";
             if(o!=null){
                permisos = ((Usuario) o).getPermisosPredeterminados();
             }
            String jSon = "";
            String text = "";
            if(o!=null){
                 text = ((Usuario) o).getCedula();
            }
            ArrayList a = new ArrayList();
            switch (opc) {
                case 1:
                   
                        Service.documentosConsultar(documentos);
                         a = new ArrayList();
                        for (int i = 0; i < documentos.size(); i++) {

                            Documento d1 = (Documento) documentos.get(i);
                            Object [] temp = datos(d1, (o != null), false,text);
                             if(temp!=null){
                                 a.add(temp);
                             }
                        }
                        out.println(gSon.toJson(a.toArray()));
                   

                    break;
                case 2:
                   
                        String texto = request.getParameter("p2");
                        Service.documentosConsultarAutor(documentos, texto);

                        for (int i = 0; i < documentos.size(); i++) {

                            Documento d1 = (Documento) documentos.get(i);
                            Object [] temp = datos(d1, (o != null), false,text);
                             if(temp!=null){
                                 a.add(temp);
                             }
                        }
                        out.println(gSon.toJson(a.toArray()));
                   
                    break;
                case 3:
                    
                        String texto2 = request.getParameter("p2");
                        Service.documentosConsultarTitulo(documentos, texto2);

                        for (int i = 0; i < documentos.size(); i++) {

                            Documento d1 = (Documento) documentos.get(i);
                            Object [] temp = datos(d1, (o != null), false,text);
                             if(temp!=null){
                                 a.add(temp);
                             }
                        }
                        out.println(gSon.toJson(a.toArray()));
                     
                    break;
                case 4:
                    Documento doc = new Documento();

                    out.println(gSon.toJson(headers()));
                    break;
                case 5:

                    if ( permisos.charAt(45) == '1') { 

                        Service.reservasConsultar(documentos, text);

                        for (int i = 0; i < documentos.size(); i++) {

                            Documento d1 = (Documento) documentos.get(i);
                            Object [] temp = datos(d1, (o != null), true,text);
                             if(temp!=null){
                                 a.add(temp);
                             }
                        }
                        out.println(gSon.toJson(a.toArray()));
                    }else{
                         out.println(false);
                    }


                    break;
                case 6:

                    if (permisos.charAt(40) == '1') { 
                        String p = ((Usuario) o).getCedula();
                        String p2 = request.getParameter("p2");
                        Service.reservaHacer(p, p2);
                        out.println(true);
                    } else {
                        out.println(false);

                    }


                    break;
                case 7:

                    if ( permisos.charAt(42) == '1') { 
                        String p3 = request.getParameter("p2");
                        Service.reservaCancelar(p3);
                        out.println(true);
                    } else {
                        out.println(false);
                    }


                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            out.println(e);
        }
    }

    public Object[] datos(Documento d, boolean logged, boolean miRsv,String user)  {
        boolean alreadyReserved = false;
        Object[] arreglo = null;
        String sol = d.getIdDocumento();
        if (sol!=null){
            arreglo = new Object[11];
            arreglo[0] = (d.getTitulo());
            arreglo[1] = (d.getAutor());
            arreglo[2] = (d.getDescriptores());
            arreglo[3] = d.getTotales() - (d.getSolicitados()+d.getPrestados());
            ArrayList documentos = new ArrayList();
            try{
                Service.reservasConsultar(documentos, user);
                alreadyReserved =contains( documentos,d);
            }
            catch(Exception ex){
                alreadyReserved = false;
            }
            if (d.getTotales() - d.getPrestados() != 0 && logged && !miRsv && !alreadyReserved) {
                arreglo[4] = ("<input type='checkbox' id='" + d.getIdDocumento() + "' value='" + d.getIdDocumento() + "'></input>");
            } else if (miRsv && alreadyReserved) {
                arreglo[4] = "<input class='btnCancelarRes' type='button' id='" + d.getIdSolicitud() + "' value='Cancelar'></input>";
            }else {
                arreglo[4] = "No se encuentra logueado o ya ha reservado este libro.";
            }
            if (d.isVirtual()){
                 arreglo[5] = ("<a href='#' id='" + d.getIdDocumento() + "' value='" + d.getIdDocumento() + "'>Descargar</a>");
            }else{
                 arreglo[5] = "El documento no cuenta con versión virtual.";
            }
        }
        return arreglo;
    }
public boolean contains(ArrayList documentos,Documento d){
    for(int i = 0;i < documentos.size();i++){
        if( ((Documento)documentos.get(i)).getIdDocumento().equals(d.getIdDocumento())){
            return true;
        }
    }
    return false;
}

    public Object[] headers() {

        Object[] array = {"Titulo", "Autor", "Descriptores", "Disponibles", "Reservas", "Link"};

        return array;

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
